﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using XiAnAirport.BUS;
using XiAnAirport.BUS.Mqtt;
using XiAnAirport.ElevatorWebSocket;
using XiAnAirport.Models;

namespace XiAnAirport.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class DeviceController : ControllerBase
    {
        public IHttpContextAccessor _contextAccessor;
        static IWebSocketManage _webSocketManage;
        private JwtSettings _jwtSettings;
        public DeviceController(IHttpContextAccessor contextAccessor, IWebSocketManage webSocketManage, IOptions<JwtSettings> jwtSettingsAccesser)
        {
            _contextAccessor = contextAccessor;
            _jwtSettings = jwtSettingsAccesser.Value;
        }

        /// <summary>
        /// 新增设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("AddDevice")]
        public ResponseMessage AddDevice(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.AddElevator(elevator);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "新增设备信息:" + elevator.elevatorName;
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "新增设备信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "新增电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }


        /// <summary>
        /// 编辑设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("UpdateDevice")]
        public ResponseMessage UpdateDevice(Elevator elevatorinfo)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.EditElevator(elevatorinfo);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "修改设备信息:" + elevatorinfo.elevatorName;
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "修改设备信息异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 删除设备信息
        /// </summary>
        /// <param name="elevator">设备id</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("DelDevice")]
        public ResponseMessage DelDevice(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.DelElevator(elevator.id);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "删除设备信息:" + elevator.elevatorName;
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "删除设备信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "删除电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 查询设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryDeviceList")]
        public ResponseMessage QueryDeviceList(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                message = BUS.QueryElevator(elevator);
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "查询电梯信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 查询设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryDeviceListByArea")]
        public ResponseMessage QueryDeviceListByArea(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                message = BUS.QueryElevatorByArea(elevator);
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "查询电梯信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 载入设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("LoadDeviceInfo")]
        public ResponseMessage LoadDeviceInfo(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.LoadElevator(elevator.id);
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "载入电梯信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "载入电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 清理设备信息
        /// </summary>
        /// <param name="elevator">设备信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("CleanUpData")]
        public ResponseMessage CleanUpData()
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.CleanUpElevator();
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "清除所有设备信息";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "清理设备信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "清理所有设备信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 新增设备区域绑定信息
        /// </summary>
        /// <param name="positioninfo">区域信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("AddElevatorPosition")]
        public ResponseMessage AddElevatorPosition(ElevatorPosition positioninfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                string username = HttpContext.Session.GetString("UserName").ToString();
                positioninfo.creationPerson = username;
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                message = BUS.AddElevatorPosition(positioninfo);
                if (message.errcode == 0)
                {
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "新增设备" + positioninfo.elevatorName + "区域绑定信息";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "新增电梯区域绑定信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "新增电梯区域绑定信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 修改电梯区域绑定信息
        /// </summary>
        /// <param name="positioninfo">区域信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("EditElevatorPosition")]
        public ResponseMessage EditElevatorPosition(ElevatorPosition positioninfo)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.EditElevatorPosition(positioninfo);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "修改设备" + positioninfo.elevatorName + "区域绑定信息";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "修改设备区域绑定信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "修改设备区域绑定信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 删除电梯区域绑定信息
        /// </summary>
        /// <param name="positioninfo">区域电梯绑定信息</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("DelElevatorPosition")]
        public ResponseMessage DelElevatorPosition(ElevatorPosition positioninfo)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.DelElevatorPosition(positioninfo.id);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "删除设备" + positioninfo.elevatorName + "区域绑定信息";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "删除设备区域绑定信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "删除设备区域绑定信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 查询电梯状态(通过缓存)
        /// </summary>
        /// <param name="stateinfo">电梯状态</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryElevatorState")]
        public ResponseMessage QueryElevatorState(ElevatorState stateinfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorStateBUS mBUS = new ElevatorStateBUS();
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                List<ElevatorState> list = mBUS.GetData();
                message = BUS.QueryElevatorState(stateinfo, list);
                if (stateinfo.Recordhead == -1 && stateinfo.Recordtail == -1)
                {
                    message.total = ElevatorStateBUS.state_list.Count;
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "查询电梯状态失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 载入电梯详情信息（通过缓存）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("LoadElevatorStateInfo")]
        public ResponseMessage LoadElevatorStateInfo(Elevator elevatorinfo)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorStateBUS BUS = new ElevatorStateBUS();
                LiftStateALL elevatorState = BUS.GetLiftStateDetail(elevatorinfo.id);
                message.data = elevatorState;
                message.errcode = 0;
                message.errmsg = "";
                message.total = 1;
            }
            catch (Exception e)
            {
                message.errcode = 1;
                message.errmsg = "载入电梯详情信息失败";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "载入电梯信息";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 批量删除设备信息
        /// </summary>
        /// <param name="elevator">设备id</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("BatchDelDevice")]
        public ResponseMessage BatchDelDevice(string ids)
        {
            ResponseMessage message = new ResponseMessage();
            ElevatorAreaBUS BUS = new ElevatorAreaBUS();
            try
            {
                message = BUS.BatchDelElevator(ids);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "批量删除设备";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "批量删除设备异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "批量删除设备";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 远程锁梯
        /// </summary>
        /// <param name="elevator">设备id</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("RemoteLockLadder")]
        public async Task<ResponseMessage> RemoteLockLadder(RemoteLockLadderInfo remoteLockLadderInfo)
        {
            ResponseMessage message = new ResponseMessage();
            MqttServerBUS BUS = new MqttServerBUS();
            try
            {
                RemoteLockLadderInfo remoteLockLadderInfo1 = new RemoteLockLadderInfo();
                remoteLockLadderInfo1.updateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                remoteLockLadderInfo1.opcNO = remoteLockLadderInfo.opcNO;
                remoteLockLadderInfo1.LockLadder = remoteLockLadderInfo.LockLadder;
                string Mess = JsonConvert.SerializeObject(remoteLockLadderInfo1);
                string version = AppSettingsHelper.Configuration["MqttServer:Version"];
                await BUS.PublicAsyncMessage(version + "/KoneDeviceControl", Mess, 0);
                 //FXMqttShareClient.control.Add(remoteLockLadderInfo.opcNO);

                try
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    LockLog operationLog = new LockLog();
                    operationLog.operation = remoteLockLadderInfo.opcNO + "远程锁梯";
                    operationLog.operatorName = username;
                    logBUS.InsertLockLog(operationLog);
                }
                catch (Exception ex)
                {
                    LogHelper.Log("远程锁梯操作日志异常" + ex.ToString());
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "远程锁梯异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log("远程锁梯异常信息："+e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "远程锁梯";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 清除折次数
        /// </summary>
        /// <param name="elevator">设备id</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("Clearbend")]
        public ResponseMessage Clearbend(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                message = BUS.Clearbend(elevator.id);
                if (message.errcode == 0)
                {
                    ElevatorStateBUS elevatorStateBUS = new ElevatorStateBUS();
                    elevatorStateBUS.ClearBend(elevator.opcNO);
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "清除" + elevator.elevatorName + "折弯次数";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "清除折弯次数异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "清除折弯次数";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }

        /// <summary>
        /// 查询电梯类型
        /// </summary>
        /// <returns>success</returns>
        [HttpPost]
        [Route("QueryElevatorType")]
        public ResponseMessage QueryElevatorType()
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorAreaBUS elevatorAreaBUS = new ElevatorAreaBUS();
                message = elevatorAreaBUS.QueryElevatorType();
            }
            catch (Exception ex)
            {
                message.errcode = 3;
                message.errmsg = "查询电梯类型异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(ex.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询电梯类型";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }
            return message;
        }

        /// <summary>
        /// 清除累计运行次数
        /// </summary>
        /// <param name="elevator">设备id</param>
        /// <returns>success</returns>
        [HttpPost]
        [Route("ClearRunsSum")]
        public ResponseMessage ClearRunsSum(Elevator elevator)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                ElevatorAreaBUS BUS = new ElevatorAreaBUS();
                message = BUS.ClearRunsSum(elevator.id);
                if (message.errcode == 0)
                {
                    string username = HttpContext.Session.GetString("UserName").ToString();
                    LogBUS logBUS = new LogBUS();
                    OperationLog operationLog = new OperationLog();
                    operationLog.operation = "清除" + elevator.elevatorName + "累计运行次数";
                    operationLog.operatorName = username;
                    logBUS.InsertOperationLog(operationLog);
                }
            }
            catch (Exception e)
            {
                message.errcode = 3;
                message.errmsg = "清除累计运行次数异常";
                message.data = null;
                message.total = 0;
                LogHelper.Log(e.ToString());
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "清除累计运行次数";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
            }

            return message;
        }
    }
}
